using System.Collections.Generic;
using System.Text;
using System;
using System.Security.Cryptography;

namespace Timesheet.Common
{
    public class PasswordUtils
    {
        private static readonly Random _rng = new Random();
        private static string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        public static string RandomString(int size)
        {
            char[] buffer = new char[size];

            for (int i = 0; i < size; i++)
            {
                buffer[i] = _chars[_rng.Next(_chars.Length)];
            }
            return new string(buffer);
        }
        /**
         * The byte[] returned by MessageDigest does not have a nice
         * textual representation, so some form of encoding is usually performed.
         */
        private static String hexEncode(byte[] input)
        {
            StringBuilder result = new StringBuilder();
            char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            for (int idx = 0; idx < input.Length; ++idx)
            {
                byte b = input[idx];
                result.Append(digits[(b & 0xf0) >> 4]);
                result.Append(digits[b & 0x0f]);
            }
            return result.ToString();
        }

        private static String base64Encode(byte[] input)
        {
            return System.Convert.ToBase64String(input);
        }

        public static String getHashPassword(String password)
        {
            Byte[] inputBytes = Encoding.UTF8.GetBytes(password+"");
            SHA256 mySHA256 = SHA256Managed.Create();
            byte[] hash = mySHA256.ComputeHash(inputBytes);
            return base64Encode(hash);
        }
    }
}
